<?php

namespace addons\shopro\service;

use app\admin\model\shopro\Code;
use app\admin\model\shopro\order\Order;

/**
 * 订单Code服务类
 */
class OrderCode
{
    /**
     * 获取订单的codes
     * 
     * @param int|object $order 订单ID或订单对象
     * @return array
     */
    public static function getOrderCodes($order)
    {
        if (is_numeric($order)) {
            $order = Order::find($order);
        }
        
        if (!$order) {
            return [];
        }
        
        return Code::getCodesByOrderId($order->id);
    }

    /**
     * 获取订单codes的字符串形式
     * 
     * @param int|object $order 订单ID或订单对象
     * @return string
     */
    public static function getOrderCodesString($order)
    {
        $codes = self::getOrderCodes($order);
        return implode(',', $codes);
    }

    /**
     * 检查订单是否有codes
     * 
     * @param int|object $order 订单ID或订单对象
     * @return bool
     */
    public static function hasOrderCodes($order)
    {
        $codes = self::getOrderCodes($order);
        return !empty($codes);
    }

    /**
     * 根据code查找订单ID
     * 
     * @param string $code
     * @return int|null
     */
    public static function getOrderIdByCode($code)
    {
        return Code::getOrderIdByCode($code);
    }

    /**
     * 根据code查找订单
     * 
     * @param string $code
     * @return object|null
     */
    public static function findOrderByCode($code)
    {
        $orderId = self::getOrderIdByCode($code);
        if (!$orderId) {
            return null;
        }
        
        return Order::find($orderId);
    }

    /**
     * 验证code是否存在
     * 
     * @param string $code
     * @return bool
     */
    public static function isValidCode($code)
    {
        return Code::codeExists($code);
    }

    /**
     * 获取code的详细信息
     * 
     * @param string $code
     * @return array|null
     */
    public static function getCodeInfo($code)
    {
        $order = self::findOrderByCode($code);
        if (!$order) {
            return null;
        }
        
        $codes = self::getOrderCodes($order);
        if (!in_array($code, $codes)) {
            return null;
        }
        
        return [
            'code' => $code,
            'order_id' => $order->id,
            'order_sn' => $order->order_sn,
            'user_id' => $order->user_id,
            'pay_fee' => $order->pay_fee,
            'status' => $order->status,
            'all_codes' => $codes
        ];
    }

    /**
     * 获取code统计信息
     * 
     * @return array
     */
    public static function getCodeStats()
    {
        return Code::getCodeStats();
    }

    /**
     * 手动为订单生成codes（管理员功能）
     * 
     * @param int $orderId 订单ID
     * @param int $count 生成数量
     * @return array
     */
    public static function manualGenerateCodes($orderId, $count)
    {
        $order = Order::find($orderId);
        if (!$order) {
            throw new \Exception('订单不存在');
        }

        // 检查是否已经生成过codes
        $existingCodes = self::getOrderCodes($order);
        if (!empty($existingCodes)) {
            throw new \Exception('该订单已经生成过codes');
        }

        try {
            $codes = Code::generateCodes($orderId, $count);
            
            // 更新订单ext字段
            $ext = $order->ext ?: [];
            $ext['order_codes'] = implode(',', $codes);
            $ext['order_codes_generated_time'] = time();
            $order->ext = $ext;
            $order->save();
            
            return $codes;
        } catch (\Exception $e) {
            throw new \Exception('生成codes失败: ' . $e->getMessage());
        }
    }
}
